package com.hadluo.qq.server.service;

import com.hadluo.qq.server.config.ChatWebSocketHandler;
import com.hadluo.qq.server.entity.Friendship;
import com.hadluo.qq.server.entity.User;
import com.hadluo.qq.server.mapper.FriendshipMapper;
import com.hadluo.qq.server.mapper.UserMapper;
import com.hadluo.qq.server.websocket.ChatWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import com.hadluo.qq.server.entity.Message;
import com.hadluo.qq.server.vo.FriendVO;
import java.util.Date;

/**
 * 好友关系服务
 * @author hadluo
 */
@Service
public class FriendshipService {
    @Autowired
    private FriendshipMapper friendshipMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;

    /**
     * 添加好友
     * @param userQQNumber 用户QQ号
     * @param friendQQNumber 好友QQ号
     * @return 添加结果
     */
    @Transactional
    public boolean addFriend(String userQQNumber, String friendQQNumber) {
        // 验证用户和好友是否存在
        User user = userMapper.selectByQQNumber(userQQNumber);
        User friend = userMapper.selectByQQNumber(friendQQNumber);

        if (user == null || friend == null) {
            return false;
        }

        // 检查是否已经是好友
        Friendship existingFriendship = friendshipMapper.selectByUserIdAndFriendId(user.getId(), friend.getId());
        if (existingFriendship != null) {
            return false;
        }

        // 创建A->B的好友关系
        Friendship friendship1 = new Friendship();
        friendship1.setUserId(user.getId());
        friendship1.setFriendId(friend.getId());
        friendship1.setStatus(1); // 直接设置为已确认状态
        friendship1.setCreateTime(new Date());
        friendship1.setUpdateTime(new Date());

        // 创建B->A的好友关系
        Friendship friendship2 = new Friendship();
        friendship2.setUserId(friend.getId());
        friendship2.setFriendId(user.getId());
        friendship2.setStatus(1); // 直接设置为已确认状态
        friendship2.setCreateTime(new Date());
        friendship2.setUpdateTime(new Date());

        // 插入双向好友关系
        boolean success = friendshipMapper.insert(friendship1) > 0 && friendshipMapper.insert(friendship2) > 0;

        // 如果添加成功，发送WebSocket通知给被添加的好友
        if (success) {
            Message notification = new Message();
            notification.setType("friend_added");
            notification.setSenderId(user.getId());
            notification.setReceiverId(friend.getId());
            notification.setContent(user.getNickname() + "添加您为好友");
            notification.setCreateTime(new Date());

            chatWebSocketHandler.sendMessageToUser(friend.getId(), notification);
        }

        return success;
    }

    /**
     * 获取用户的好友列表
     * @param qqNumber 用户QQ号
     * @return 好友列表数据
     */
    public List<FriendVO> getFriendList(String qqNumber) {
        // 获取用户信息
        User user = userMapper.selectByQQNumber(qqNumber);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 获取好友关系列表
        List<Friendship> friendships = friendshipMapper.selectByUserId(user.getId());
        List<FriendVO> friendList = new ArrayList<>();

        for (Friendship friendship : friendships) {
            // 获取好友信息
            User friend = userMapper.selectById(friendship.getFriendId());
            if (friend == null) continue;

            // 获取最近一条聊天记录
            List<Message> messages = messageService.getChatHistory(user.getId(), friend.getId(), 1);
            Message lastMessage = messages.isEmpty() ? null : messages.get(0);

            // 构建好友信息
            FriendVO friendInfo = new FriendVO();
            friendInfo.setId(friend.getId());
            friendInfo.setQqNumber(friend.getQqNumber());
            friendInfo.setNickname(friend.getNickname());
            friendInfo.setAvatar(friend.getAvatar());
            friendInfo.setSignature(friend.getSignature());
            // 使用WebSocket连接状态判断用户是否在线
            friendInfo.setStatus(ChatWebSocket.isUserOnline(friend.getQqNumber()) ? 1 : 0);
            friendInfo.setRemark(friendship.getRemark());

            // 添加最近消息信息
            if (lastMessage != null) {
                friendInfo.setLastMessage(lastMessage.getContent());
                friendInfo.setLastMessageTime(lastMessage.getCreateTime().getTime());
            }

            friendList.add(friendInfo);
        }

        return friendList;
    }

    /**
     * 获取好友详细信息
     * @param userQQNumber 用户QQ号
     * @param friendQQNumber 好友QQ号
     * @return 好友详细信息
     */
    public FriendVO getFriendDetail(String userQQNumber, String friendQQNumber) {
        // 验证用户和好友是否存在
        User user = userMapper.selectByQQNumber(userQQNumber);
        User friend = userMapper.selectByQQNumber(friendQQNumber);

        if (user == null || friend == null) {
            return null;
        }

        // 检查是否是好友关系
        Friendship friendship = friendshipMapper.selectByUserIdAndFriendId(user.getId(), friend.getId());
        if (friendship == null) {
            return null;
        }

        // 构建好友详细信息
        FriendVO friendInfo = new FriendVO();
        friendInfo.setId(friend.getId());
        friendInfo.setQqNumber(friend.getQqNumber());
        friendInfo.setNickname(friend.getNickname());
        friendInfo.setAvatar(friend.getAvatar());
        friendInfo.setSignature(friend.getSignature());
        // 使用WebSocket连接状态判断用户是否在线
        friendInfo.setStatus(ChatWebSocket.isUserOnline(friend.getQqNumber()) ? 1 : 0);
        friendInfo.setRemark(friendship.getRemark());

        return friendInfo;
    }

    /**
     * 删除好友关系
     * @param userQQNumber 用户QQ号
     * @param friendQQNumber 好友QQ号
     * @return 删除结果
     */
    @Transactional
    public boolean deleteFriend(String userQQNumber, String friendQQNumber) {
        // 验证用户和好友是否存在
        User user = userMapper.selectByQQNumber(userQQNumber);
        User friend = userMapper.selectByQQNumber(friendQQNumber);

        if (user == null || friend == null) {
            return false;
        }

        // 删除好友关系
        return friendshipMapper.deleteByUserIdAndFriendId(user.getId(), friend.getId()) > 0;
    }
}